import store from '@/store'
import { NavigationGuard } from 'vue-router'
import Vue from 'vue'
import NP from 'nprogress'
import { getProperties } from '@/api/properties'
import { getInitOptions, setInitOptions } from '@/config/init'

const whiteList = ['/login', '/error/**'] // ant style wildcat

const frontGuard: NavigationGuard = function (to, from, next) {
  NP.start()
  const auth = Vue.prototype.$auth

  if (to.path === '/config') {
    next()
    return
  }
  if (!getInitOptions()) {
    // setInitOptions({
    //   api: 'http://dev.rawacloud.com:60010',
    //   previewUrl: 'http://dev.rawacloud.com:60030'
    // })
    // location.reload()
    next('/config')
    return
  }

  const properties = (store.state as any)?.app?.properties
  if (!properties) {
    getProperties().then(data => {
      store.commit('app/setProperties', data || null)
    })
  }

  // 白名单或未设置权限， 不验证
  if (onWhiteList(to.path) || (!to.meta?.pid)) {
    next()
    return
  }
  // 权限控制
  auth.access(to.meta?.pid).then((pass: boolean) => {
    if (pass) {
      const space = (store.state as any)?.app?.currentSpace
      if (to.path === '/' && space) {
        next(space?.type === 'user' ? '/docs' : `/ent/${space.ownId}/docs`)
      } else {
        next()
      }
    } else {
      next({ path: '/error/403' })
      NP.done()
    }
  }).catch(() => {
    NP.done()
    next()
  })
}

function onWhiteList (path: string) {
  const convertRegEx = (expr: string) => {
    return new RegExp('^' +
      (expr || '')
        .replace(/\*\*/g, '#__#')
        .replace(/\*/g, '[^/]*')
        .replace(/#__#/g, '.*') +
      '$')
  }
  return whiteList.some(v => convertRegEx(v).test(path))
}

export default frontGuard
